<?php
/**
 * Created by PhpStorm.
 * User: liuhong
 * Date: 2019-04-08
 * Time: 15:03
 */

namespace app\service;
use app\common\model\Daily;
use app\model\UserModel;
use app\model\UserWechatModel;
use think\Db;
use think\Exception;

/**
 * 用户服务
 * Class UserService
 * @package app\service
 */
class UserService extends BaseService
{
    protected $userModel;
    protected $userWechatModel;
    public function __construct()
    {
       $this->userModel=new UserModel();
       $this->userWechatModel=new UserWechatModel();
    }
    
    /**
     * 查询用户信息
     * @param $where
     * @param $filed
     * @return array|bool|false|\PDOStatement|string|\think\Model
     */
    public function findUser($where,$filed=null){
        try{
           $re= $this->userModel
               ->field($filed)
               ->where($where)
               ->find();
           if($re){
               return $re->toArray();
           }else{
               return array();
           }

        }catch (Exception $ex){
            LogService::S()->writeLog('Exception',$ex->getMessage());
            return false;
        }
    }

    /**查询用户信息
     * @param $where
     * @param null $filed
     * @return bool|mixed
     */
    public function getUserFiled($where,$filed=null){
        try{
            return $this->userModel
                ->field($filed)
                ->where($where)
                ->value($filed);
        }catch (Exception $ex){
            LogService::S()->writeLog('Exception',$ex->getMessage());
            return false;
        }
    }

    /**查询用户信息
     * @param $where
     * @param null $filed
     * @return bool|mixed
     */
    public function getArrayUserFiled($where,$filed=null){
        try{
            return $this->userModel
                ->field($filed)
                ->where($where)
                ->column($filed);
        }catch (Exception $ex){
            LogService::S()->writeLog('Exception',$ex->getMessage());
            return false;
        }
    }

    public function findUserWechat($where,$filed=null){
        try{
            return $this->userModel
                ->field($filed)
                ->where($where)
                ->find()
                ->toArray();
        }catch (Exception $ex){
            LogService::S()->writeLog('Exception',$ex->getMessage());
            return false;
        }
    }

    /**
     * 查询多条用户信息
     * @param $where
     * @param $filed
     * @return array|bool
     */
    public function selectUserInfo($where,$filed){
        try{
            return $this->userModel
                ->field($filed)
                ->where($where)
                ->select()
                ->toArray();
        }catch (Exception $ex){
            LogService::S()->writeLog('Exception',$ex->getMessage());
            return false;
        }
    }

    /**
     * 修改用户信息
     * @param $where
     * @param $save
     * @return bool|false|int
     */
    public function saveUserInfo($where,$save){
        try{
            return $this->userModel->save($save,$where);
        }catch (Exception $ex){
            LogService::S()->writeLog('Exception',$ex->getMessage());
            return false;
        }
    }


    /**
     * 字段自增
     * @param $uid
     * @param $value
     * @param $filed
     * @return int|true
     * @throws Exception
     */
    public function increFiled($uid,$value,$filed){
        try{
            return $this->userModel->where('id',$uid)->setInc($filed,$value);
        }catch (Exception $ex){
            LogService::S()->writeLog('Exception',$ex->getMessage());
            return false;
        }
    }

    /**
     * 字段自增
     * @param $uid
     * @param $value
     * @param $filed
     * @return int|true
     * @throws Exception
     */
    public function decFiled($uid,$value,$filed){
        try{
            return $this->userModel->where('id',$uid)->setDec($filed,$value);
        }catch (Exception $ex){
            LogService::S()->writeLog('Exception',$ex->getMessage());
            return false;
        }
    }


    /**
     * 微信登录后拿到微信的原始用户信息，处理得到uid
     * @param $info
     * @return bool|int|mixed|string
     */
    public function handleWechatUser ($info) {
        try{
            unset($info['privilege']);
            $wechatUser = Db::name('user_wechat')->where('openid',$info['openid'])->find();
            if($wechatUser) {
                $this->userWechatModel
                    ->where('openid',$info['openid'])
                    ->update($info);
            }else{
                $this->userWechatModel->insertGetId($info);
            }
            $wechatUser = Db::name('user_wechat')->where('openid',$info['openid'])->find();
            if(!$wechatUser['uid']) {
                Daily::inc('register');
                $userInfo = [
                    'nickname' => $info['nickname'],
                    'headimgurl' => $info['headimgurl'],
                    'mall_id' => $info['mall_id'],
                    'create_time' => time(),
                    'openid_main' => $info['openid'],
                    'uniid' => md5($info['openid'].time().uniqid())
                ];
                $user_id = $this->userModel->insertGetId($userInfo);
                Db::name('user_wechat')->where('openid',$info['openid'])->update([
                    'uid' => $user_id
                ]);
            }else{
                $user_id = $wechatUser['uid'];
            }
            return $user_id;
        }catch (Exception $ex){
            LogService::S()->writeLog('Exception',$ex->getMessage());
            return false;
        }
    }


    /**
     * 返回该用户的所有下级列表
     * @param $uid
     * @return array|bool
     */
    public function backAllXiaji($uid){
        try{
            $max=2; //最多显示多少级别
            $i=1; //从一级开始计算
            $uidArray=array($uid);
            $filed='id';
            $userInfo=$this->userModel->where(array('refer_id'=>$uid))->column($filed);//UserService::S()->queryMemberInfo($where,$filed);
            $uidArray=array_merge($uidArray,$userInfo);

            while ($userInfo){
                $referWhere['refer_id']=array('in',$userInfo);
                $userInfo=$this->userModel->where($referWhere)->column($filed);//UserService::S()->queryMemberInfo($referWhere,$filed);
                if(!empty($userInfo)){
                    $uidArray=array_merge($uidArray,$userInfo);
                }
                $i++;
                if($i==$max){
                    break;
                }
            }
            return $uidArray;
        }catch (Exception $ex){
            LogService::S()->writeLog('Exception',$ex->getMessage());
            return false;
        }

    }

    /**
     * @param $uid
     * @param null $filed
     * @return array|bool|false|\PDOStatement|string|\think\Model
     */
    public function findWechatUser($uid,$filed=null){
        try{
            if(empty($filed)){
                $filed='uid,openid';
            }
            $wechatUserModel=Db::name('user_wechat');
            return $wechatUserModel->field($filed)->where('uid',$uid)->find();
        }catch (Exception $ex){
            LogService::S()->writeLog('Exception',$ex->getMessage());
            return false;
        }
    }

    /**
     * @param $where
     * @param null $filed
     * @return bool|mixed
     */
    public function getWechatUserFiled($where,$filed=null){
        try{
            if(empty($filed)){
                $filed='openid';
            }
            $wechatUserModel=Db::name('user_wechat');
            return $wechatUserModel->where($where)->value($filed);
        }catch (Exception $ex){
            LogService::S()->writeLog('Exception',$ex->getMessage());
            return false;
        }
    }

    /**
     * @param $where
     * @param null $filed
     * @return bool|mixed
     */
    public function getWechatUserInfo($where,$filed=null){
        try{
            if(empty($filed)){
                $filed='openid';
            }
            $wechatUserModel=Db::name('user_wechat');
            return $wechatUserModel->where($where)->find();
        }catch (Exception $ex){
            LogService::S()->writeLog('Exception',$ex->getMessage());
            return false;
        }
    }


    /**
     * 返回所有类型对应ID
     * @return array|bool
     */
    public function backAllGradeArray(){
        try{
            $gradeInfo=Db::name('grade')->select()->toArray();
            $gradeAll=array();
            foreach ($gradeInfo as $k=>$v){
                $gradeAll[$v['id']]=$v['grade_name'];
            }
            return $gradeAll;
        }catch (Exception $ex){
            LogService::S()->writeLog('Exception',$ex->getMessage());
            return false;
        }

    }

    /**
     * @return array
     */
    public static function getInstance()
    {
        return self::$Instance;
    }




}